<template>
    <div class="chart_Kline" ref="chartKlineDoc" @dblclick="dblclickChart" @contextmenu.prevent="handleRightClick">
        <div class="hqchart" ref="hqchart"></div>
        <diao_msg ref="diaoMsg" />
    </div>
</template>

<script setup>
const fs = require('fs');
const path = require('path');
const { ipcRenderer } = require('electron');
import { ref, reactive, watch, defineProps, onUnmounted, onMounted } from 'vue';
import moment from 'moment'
import { Chart } from 'hqchart'
import diao_msg from '@/components/view_list/diao_msg.vue'
import 'hqchart/src/jscommon/umychart.resource/css/tools.css'
import 'hqchart/src/jscommon/umychart.resource/font/iconfont.css'
moment.locale("zh-cn");
import HQChart from 'hqchart'
HQChart.Chart.JSConsole.Chart.Log = () => { }
HQChart.Chart.JSConsole.Complier.Log = () => { }



import { MinuteOption, KLineOption } from './utils/option.js'
import { mainStore, chartStore } from '@/store/index.js'
import bus from '@/utils/bus.js'
let targetObjPath = path.resolve(__dirname, '../../../../../../static/target/target.json');
if (process.env.NODE_ENV == 'production') {
    targetObjPath = path.resolve(__dirname, '../../static/target/target.json');
}
const content = fs.readFileSync(targetObjPath, 'utf-8');
let targetData = JSON.parse(content)
const DefaultTarget = [targetData['MA'], targetData['MACD'], targetData['VOL']]
import tiaoJianTxt from '@/utils/tiaojiandan.js'


const props = defineProps(['minLineVal']);

const hauxianNum = ref(0)
const diaoMsg = ref(null)
const chartKlineDoc = ref(null)
const hqchart = ref(null)
const ChartObj = reactive({ Kline: null, zoushi: null })
const KlineArr = ref([])
const NetworkFilterCallback = ref(null)
const KlineOptionInfo = ref({})
const MinuOptionInfo = ref({})
const istodayDataKline = ref(localStorage.getItem('istodayDataKline') == 1 ? true : false)
const klineDtartDate = ref(null)
const minuDay = ref(1)
const DrawPictureList = ref([])
const xuanzhongDrawPictureList = ref(null)





const storeMain = mainStore()
const storeChart = chartStore()


watch(() => [storeChart.KlineData, storeChart.selecteHangeQingData, storeChart.TradetimeList, storeChart.selectbodyChartListTab], ([newKlineData, newselecteHangeQingData, newTradetimeList, selectbodyChartListTab], [oldKlineData]) => {
    if (selectbodyChartListTab == '分时图' && !ChartObj.zoushi) {
        if (newKlineData.length > 0 && newselecteHangeQingData && newTradetimeList) {
            // const threeDaysAgoMidnight = moment(storeChart.TradetimeList[0].start_time * 1000).subtract(1, 'days').startOf('day');
            // const threeDaysAgoMidnight = moment(storeChart.TradetimeList[0].start_time * 1000).subtract(1, 'days');
            // const timestamp = threeDaysAgoMidnight.unix();
            const timestamp = storeChart.TradetimeList[0].start_time
            KlineArr.value = [...newKlineData, ...KlineArr.value]
            if (newKlineData[0].time <= timestamp) {
                console.log(`output->storeChart.selecteHangeQingData.closedYes`, storeChart.selecteHangeQingData.closedYes)
                showToolTip = false
                CreateMinuteChart()
                OnSize();
            } else {
                storeChart.hangqingMqtt.publish(`40;${storeMain.selectHeyue.heyue_bh};${props.minLineVal};${storeChart.hangqingMqtt.clientId};${newKlineData[0].time};`)
            }
        }
    } else if (selectbodyChartListTab == '分时图' && ChartObj.zoushi && newKlineData.length > 0) {
        // const threeDaysAgoMidnight = moment(storeChart.TradetimeList[0].start_time * 1000).subtract(1, 'days').startOf('day');
        // const threeDaysAgoMidnight = moment(storeChart.TradetimeList[0].start_time * 1000).subtract(1, 'days');
        // const timestamp = threeDaysAgoMidnight.unix();
        const timestamp = storeChart.TradetimeList[0].start_time
        if (newKlineData[0].time > timestamp) {
            KlineArr.value = [...newKlineData, ...KlineArr.value]
            storeChart.hangqingMqtt.publish(`40;${storeMain.selectHeyue.heyue_bh};${props.minLineVal};${storeChart.hangqingMqtt.clientId};${newKlineData[0].time};`)
        }
    }
    if (selectbodyChartListTab == 'K线图' && !ChartObj.Kline) {
        if (newKlineData.length > 0 && oldKlineData.length <= 0 && newselecteHangeQingData && newTradetimeList) {
            KlineArr.value = newKlineData
            showToolTip = false
            CreateKLineChart(storeChart.klineCycle)
            OnSize();
        }
    }
})

watch(() => storeChart.KlineData, (newVal, oldVal) => {
    if (storeChart.selectbodyChartListTab == 'K线图' && newVal.length > 0 && oldVal.length > 0 && NetworkFilterCallback.value) {
        KlineArr.value = [...newVal, ...KlineArr.value]
        NetworkFilterCallback.value(setKlineHqchart(newVal))
    }
})

watch(() => storeChart.lastKLineData, (newVal) => {
    if (newVal && KlineArr.value.length > 0) {
        if (KlineArr.value[KlineArr.value.length - 1].time == newVal.time) {
            KlineArr.value[KlineArr.value.length - 1] = newVal
        } else {
            KlineArr.value.push(newVal)
        }
        if (storeChart.selectbodyChartListTab == '分时图' && ChartObj.zoushi) {
            ChartObj.zoushi.JSChartContainer.RecvMinuteData(setMinuteHqchart(KlineArr.value));
        }
        if (storeChart.selectbodyChartListTab == 'K线图' && ChartObj.Kline) {
            ChartObj.Kline.JSChartContainer.RecvMinuteRealtimeData(setKlineHqchart([newVal]));
        }
    }
})

watch(() => [storeChart.klineCycle, storeChart.KlineData], ([klineCycle, KlineData]) => {
    if (storeChart.selectbodyChartListTab == 'K线图' && KlineData.length > 0 && ChartObj.Kline) {
        ChartObj.Kline.ChangePeriod(klineCycle);
    }
})

watch(() => storeChart.selectbodyChartListTab, () => {
    DrawPictureList.value = []
})

watch(() => storeChart.selecteHangeQingData.currentPrice, (newVal) => {
    if (!newVal || DrawPictureList.value.length > 0) return;
    DrawPictureList.value.forEach(item => {
        if (item.YValue.toFixed(2) == newVal.toFixed(2)) {
            ipcRenderer.send('hua_xian_xia_dan_data', JSON.stringify(item))
        }
    })
})

bus.on('changeHeadApiVal', (v) => {
    let newVal = v.type
    if (newVal == 'clearKLineData') {
        ClearChart()
        KlineArr.value = []
    }
    if (!newVal || storeChart.selectbodyChartListTab == '分时图') return
    let index, index1
    switch (newVal) {
        // case '画线下单':
        //     ipcRenderer.send('open-huaxiadanOption',{ configInfo: JSON.stringify(storeMain.ConfigJsInfo) })
        //     break;
        case '水平放大':
            ChartObj.Kline.JSChartContainer.ChartOperator({ ID: 4 });
            break;
        case '水平压缩':
            ChartObj.Kline.JSChartContainer.ChartOperator({ ID: 3 });
            break;
        case '左翻K线':
            ChartObj.Kline.JSChartContainer.ChartOperator({ ID: 2, Step: 10 });
            break;
        case '右翻K线':
            ChartObj.Kline.JSChartContainer.ChartOperator({ ID: 1, Step: 10 });
            break;
        case '上翻合约':
            ClearChart()
            index = storeMain.heyueinfo.findIndex((item) => item.heyue_bh == storeMain.selectHeyue.heyue_bh)
            if (index <= 0) {
                storeMain.changeHeyueinfo(storeMain.heyueinfo[storeMain.heyueinfo.length - 1])
            }
            if (index > 0) {
                storeMain.changeHeyueinfo(storeMain.heyueinfo[index - 1])
            }
            bus.emit('turnOver')
            break;
        case '下翻合约':
            ClearChart()
            index1 = storeMain.heyueinfo.findIndex((item) => item.heyue_bh == storeMain.selectHeyue.heyue_bh)
            if (index1 <= storeMain.heyueinfo.length - 2) {
                storeMain.changeHeyueinfo(storeMain.heyueinfo[index1 + 1])
            }
            if (index1 > storeMain.heyueinfo.length - 2) {
                storeMain.changeHeyueinfo(storeMain.heyueinfo[0])
            }
            bus.emit('turnOver')
            break;
        case '区间选择/统计':
            ChartObj.Kline.JSChartContainer.DragMode = ChartObj.Kline.JSChartContainer.DragMode == 2 ? 1 : 2;
            break;
    }
    if (v.isxian) {
        onDrawXian(v.type)
    }
})

ipcRenderer.on('send-huaxiadanOption-data', (e, v) => {
    let LineColor, YValue
    if (v.type == '买') {
        LineColor = '#4169e1'
        YValue = storeChart.selecteHangeQingData.buy1
    }
    if (v.type == '卖') {
        LineColor = '#00d900'
        YValue = storeChart.selecteHangeQingData.seller1
    }
    if (v.type == '平') {
        LineColor = '#e4e4e4'
        YValue = storeChart.selecteHangeQingData.currentPrice
    }
    if (v.type == '反') {
        LineColor = '#ff8c00'
        YValue = storeChart.selecteHangeQingData.currentPrice
    }
    let drawPictrue =
    {
        ClassName: "ChartDrawPictureHorizontalLine",
        Value: [{ XValue: 0, YValue }],
        FrameID: 0,
        RightSpaceWidth: 2,
        Button: { SettingIcon: null },
        ButtonBGColor: "#000000",
        LineColor,
    };
    DrawPictureList.value.push({ YValue, Guid: '', LineColor, heyue_id: storeChart.selecteHangeQingData.heyue_id, ...v })
    if (ChartObj.Kline) {
        ChartObj.Kline.AddChartDrawPicture(drawPictrue);
        ChartObj.Kline.Draw();
    }
    if (ChartObj.zoushi) {
        ChartObj.zoushi.AddChartDrawPicture(drawPictrue);
        ChartObj.zoushi.Draw();
    }
})
ipcRenderer.on('edithuaTuGj', (e, v) => {
    localStorage.setItem('selectHuTuList', JSON.stringify(v))
    let arr = storeChart.toolMeun.slice(-2)
    let arr1 = storeChart.toolMeun.splice(0, 23)
    v.sort((a, b) => JSON.parse(a).idx - JSON.parse(b).idx);
    let huatuGj = v.map(item => {
        item = JSON.parse(item)
        return {
            show: true, isbar: 1, name: '', type: item.type, icon: item.icon, isxian: true
        }
    })
    storeChart.changeToolMeun([...arr1, ...huatuGj, ...arr])
})
ipcRenderer.on('right_click_msg_win', (e, v) => {
    if (ChartObj.Kline) {
        if (v.type == '画线下单') {
            ipcRenderer.send('open-huaxiadanOption')
        }
        if (v.type == '主图指标') {
            ChartObj.Kline.ChangeIndex(0, v.msg, KLineOption)
        }
        if (v.type == '副图指标') {
            if (KlineOptionInfo.value.Windows.length >= 2) {
                ChartObj.Kline.ChangeIndex(1, v.msg, KlineOptionInfo.value)
            } else {
                KlineOptionInfo.value.Windows.push({ Index: v.msg, Overlay: false })
                ChartObj.Kline.AddIndexWindow(v.msg, KlineOptionInfo.value);
            }
        }
        if (v.type == '坐标反转') {
            ChartObj.Kline.JSChartContainer.ChangeCoordinateType({ Type: 0, IsReverse: v.msg == 1 })
        }
        if (v.type == '切换到对数坐标') {
            ChartObj.Kline.JSChartContainer.ChangeCoordinateType({ Type: v.msg == 1 ? 2 : 0 })

        }
        // if (v.type == '最近1天') {

        // }
        // if (v.type == '最近2天') {

        // }
        // if (v.type == '最近5天') {

        // }
        if (v.type == '切换分时图/线') {
            storeChart.changeSelectbodyChartListTab('分时图')
            storeChart.changeHeadApiVal({ type: '分时' })
        }
        if (v.type == '增加副图子窗口') {
            KlineOptionInfo.value.Windows.push({ Index: v.msg, Overlay: false, Close: false })
            ChartObj.Kline.AddIndexWindow(v.msg, KlineOptionInfo.value);
            saveWindowIndex()
        }
        if (v.type == '删除副图子窗口' && KlineOptionInfo.value.Windows.length >= 2) {
            KlineOptionInfo.value.Windows.pop()
            ChartObj.Kline.RemoveIndexWindow(KlineOptionInfo.value.Windows.length);
            saveWindowIndex()
        }
        if (v.type == '涂鸦笔') {
            onDrawXian('涂鸦线段')
        }
        if (v.type == '分钟k线图只使用当日数据') {
            istodayDataKline.value = v.msg == 1 ? true : false
            localStorage.setItem('istodayDataKline', v.msg)
            CreateKLineChart(storeChart.klineCycle)
        }
        if (v.type == '显示未回补缺口') {
            ChartObj.Kline.JSChartContainer.ChangePriceGap({ Enable: v.msg == 1 ? '显示' : '隐藏', Count: 3 });
        }
        if (v.type == '回到最新的k线位置') {
            ChartObj.Kline.JSChartContainer.ChartOperator({ ID: 5 });
        }
        if (v.type == '指定k线起始日期') {
            klineDtartDate.value = v.msg
            CreateKLineChart(storeChart.klineCycle)
        }
        if (v.type == '区间统计/放大') {
            ChartObj.Kline.JSChartContainer.DragMode = ChartObj.Kline.JSChartContainer.DragMode == 2 ? 1 : 2;
        }

        if (v.type == '纵向压缩显示比例') {
            ChartObj.Kline.JSChartContainer.ChartOperator({ ID: 3 });
        }
        if (v.type == '纵向放大显示比例') {
            ChartObj.Kline.JSChartContainer.ChartOperator({ ID: 4 });
        }
        if (v.type == '画线买' || v.type == '画线卖') {
            hauxianNum.value = v.num
            huaxian(v.type)
        }
        if (v.type == '删除画线') {
            ChartObj.Kline.JSChartContainer.ClearChartDrawPicture({ Guid: v.msg });
        }
    }
    if (ChartObj.zoushi) {
        if (v.type == '画线下单') {
            ipcRenderer.send('open-huaxiadanOption')
        }
        if (v.type == '技术指标副图') {
            // ChartObj.zoushi.ChangeIndex(1, v.msg)
            if (MinuOptionInfo.value.Windows && MinuOptionInfo.value.Windows.length >= 1) {
                ChartObj.zoushi.ChangeIndex(2, v.msg, MinuOptionInfo.value || MinuteOption)
            } else {
                let targetOption = targetData[v.msg]
                if (targetOption) {
                    MinuOptionInfo.value.Windows = [targetOption]
                    ChartObj.zoushi.AddScriptIndexWindow(targetOption, { Window: { Close: false } });
                    localStorage.setItem('MinuWindowIndexIndex', JSON.stringify(targetOption))
                } else {
                    MinuOptionInfo.value.Windows.push({ Index: v.msg, Overlay: false, Close: false })
                    ChartObj.zoushi.AddIndexWindow(v.msg, MinuOptionInfo.value);
                }
            }
        }
        if (v.type == '历史回忆') {
            minuDay.value = v.msg
            ChartObj.zoushi.ChangeDayCount(v.msg)
        }
        if (v.type == '删除副图子窗口') {
            if (MinuOptionInfo.value.Windows.length < 1) return;
            MinuOptionInfo.value.Windows.pop()
            ChartObj.zoushi.RemoveIndexWindow(MinuOptionInfo.value.Windows.length + 2);
            localStorage.setItem('MinuWindowIndexIndex', JSON.stringify({}))
        }
        if (v.type == '切换分时图/线') {
            storeChart.changeSelectbodyChartListTab('K线图')
            storeChart.changeHeadApiVal({ type: 'K线' })
        }
    }
})
onMounted(() => {
    document.addEventListener('keydown', handlePageKey);
})

onUnmounted(() => {
    document.removeEventListener('keydown', handlePageKey);
    bus.off('changeHeadApiVal')
    ClearChart()
})

const handlePageKey = (event) => {
    if (event.key === 'PageUp') {
        ClearChart()
        let index = storeMain.heyueinfo.findIndex((item) => item.heyue_bh == storeMain.selectHeyue.heyue_bh)
        if (index <= 0) {
            storeMain.changeHeyueinfo(storeMain.heyueinfo[storeMain.heyueinfo.length - 1])
        }
        if (index > 0) {
            storeMain.changeHeyueinfo(storeMain.heyueinfo[index - 1])
        }
        bus.emit('turnOver')
    } else if (event.key === 'PageDown') {
        ClearChart()
        let index1 = storeMain.heyueinfo.findIndex((item) => item.heyue_bh == storeMain.selectHeyue.heyue_bh)
        if (index1 <= storeMain.heyueinfo.length - 2) {
            storeMain.changeHeyueinfo(storeMain.heyueinfo[index1 + 1])
        }
        if (index1 > storeMain.heyueinfo.length - 2) {
            storeMain.changeHeyueinfo(storeMain.heyueinfo[0])
        }
        bus.emit('turnOver')
    } else if (event.key === 'Delete') {
        setTimeout(() => {
            let DrawTool = localStorage.getItem('4E7EA133-D6C8-4776-9869-1DDDCC5FA744')
            if (DrawTool) {
                tiaoJianTxt.writeHuaXian(DrawTool)
                let arr = JSON.parse(DrawTool).map(item => {
                    return item.Value
                })
                arr = arr.flat()
                let obj = tiaoJianTxt.readLogs()
                obj = JSON.parse(obj)
                for (let key in obj) {
                    for (let item in obj[key]) {
                        let isgid = arr.some(subItem => subItem.Key == item)
                        if (!isgid) {
                            delete obj[key][item]
                        }
                    }
                }
                tiaoJianTxt.writeLog(JSON.stringify(obj))
            }
        }, 500);
    }
}

function huaxian(type) {
    if (storeMain.selectHeyue.zhu_bz != 1 || storeMain.selectHeyue.jiekou_id != 2) {
        diaoMsg.value.open('此合约不支持画线下单')
        return
    }
    let option = {
        LineColor: '#fa3b3b', //线段颜色
        LineWidth: 1, //线段宽度
        PointColor: '#fa3b3b' //选中点颜色
    }
    if (type == '画线卖') {
        option.LineColor = '#00dc00'
        option.PointColor = '#00dc00'
    }
    ChartObj.Kline.CreateChartDrawPicture('水平线', option);
}

async function getYvalue(event, data) {
    let DrawPicture = data.DrawPicture
    xuanzhongDrawPictureList.value = DrawPicture
    DrawPictureList.value.forEach(item => {
        let LineColor1 = DrawPicture.LineColor.toUpperCase()
        let LineColor2 = item.LineColor.toUpperCase()
        if (LineColor1 == LineColor2) {
            if (item.Guid == DrawPicture.Guid) {
                item.YValue = DrawPicture.Value[0].YValue
            }
        }
    })
    let time = moment().format('YYYY-MM-DD HH:mm:ss')
    let maimai = ''
    if (data.DrawPicture.LineColor == '#fa3b3b') {
        maimai = '买'
    }
    if (data.DrawPicture.LineColor == '#00dc00') {
        maimai = '卖'
    }
    if (!maimai) return
    let heyue_bh = storeMain.selectHeyue.heyue_bh
    let Guid = data.DrawPicture.Guid,
        price = data.DrawPicture.Value[0].YValue.toFixed(2)
    let arr = await tiaoJianTxt.readLogs()
    let obj = {}
    if (arr) {
        obj = JSON.parse(arr)
        if (obj[heyue_bh] && obj[heyue_bh][Guid]) {
            obj[heyue_bh][Guid].xiutime = time
            obj[heyue_bh][Guid].price = price
            tiaoJianTxt.writeLog(JSON.stringify(obj))
        }
    }
    setTimeout(() => {
        let DrawTool = localStorage.getItem('4E7EA133-D6C8-4776-9869-1DDDCC5FA744')
        if (DrawTool) {
            tiaoJianTxt.writeHuaXian(DrawTool)
        }
    }, 500);
}
function xuanZhongXian(event, data) {
    let DrawPicture = data.DrawPicture
    xuanzhongDrawPictureList.value = DrawPicture
    DrawPictureList.value.forEach(item => {
        let LineColor1 = DrawPicture.LineColor.toUpperCase()
        let LineColor2 = item.LineColor.toUpperCase()
        if (LineColor1 == LineColor2) {
            if (!item.Guid && item.YValue == DrawPicture.Value[0].YValue) {
                item.Guid = DrawPicture.Guid
            }
        }
    })
}

async function OnFinishDrawPicture(event, data) {
    let time = moment().format('YYYY-MM-DD HH:mm:ss')
    let maimai = ''
    if (data.DrawPicture.LineColor == '#fa3b3b') {
        maimai = '买'
    }
    if (data.DrawPicture.LineColor == '#00dc00') {
        maimai = '卖'
    }
    if (!maimai) return
    let heyue_bh = storeMain.selectHeyue.heyue_bh
    let Guid = data.DrawPicture.Guid,
        price = data.DrawPicture.Value[0].YValue.toFixed(2)
    let obj = {}
    let arr = await tiaoJianTxt.readLogs()
    setTimeout(() => {
        let DrawTool = localStorage.getItem('4E7EA133-D6C8-4776-9869-1DDDCC5FA744')
        if (DrawTool) {
            tiaoJianTxt.writeHuaXian(DrawTool)
        }
    }, 500);
    if (arr) {
        obj = JSON.parse(arr)
        if (obj[heyue_bh] && obj[heyue_bh][Guid]) {
            obj[heyue_bh][Guid].xiutime = time
            obj[heyue_bh][Guid].price = price
            tiaoJianTxt.writeLog(JSON.stringify(obj))
            return
        }
    }
    obj[heyue_bh] = {
        ...obj[heyue_bh],
        [Guid]: {
            time: time,
            state: 1,
            heyue_name: storeMain.selectHeyue.heyue_name,
            heyue_bh,
            price: price,
            maimai: maimai,
            kaiping: '开仓',
            num: hauxianNum.value,
            xiutime: null,
            Guid: Guid,
            isCHuFa: 1,
            heyue_id: storeMain.selectHeyue.heyue_id,
            heyue_zu_id: storeMain.selectHeyue.heyue_zu_id,
            jiageState: 101
        }
    }
    tiaoJianTxt.writeLog(JSON.stringify(obj))
}

const CreateKLineChart = (v) => {
    ClearChart()
    let klineOptionWindows = localStorage.getItem('klineWindowIndexIndex') ? JSON.parse(localStorage.getItem('klineWindowIndexIndex')) : []
    KLineOption.Windows = klineOptionWindows.length ? klineOptionWindows : DefaultTarget
    let option = KLineOption;
    option.ExtendChart = [
        {
            Name: "KLineTooltip",
            Create: () => {
                return new CustomTooltip();
            }
        }
    ]
    let DrawTool = tiaoJianTxt.readHuaXian()
    if (DrawTool) {
        DrawTool = JSON.parse(DrawTool)
        localStorage.setItem('4E7EA133-D6C8-4776-9869-1DDDCC5FA744', JSON.stringify(DrawTool))
    }

    option.Symbol = `${v}.ET`;
    option.Period = v;
    option.KLine.Period = v;
    option.DrawTool =     //画图工具
    {
        StorageKey: '4E7EA133-D6C8-4776-9869-1DDDCC5FA744'
    }
    let blackStyle = Chart.HQChartStyle.GetStyleConfig(
        Chart.STYLE_TYPE_ID.BLACK_ID
    );
    blackStyle.CorssCursorVPenColor = "rgba(255,255,255,0.9)";
    blackStyle.CorssCursorHPenColor = "rgba(255,255,255,0.9)";
    blackStyle.CorssCursorBGColor = "rgba(0,0,0,1)";
    blackStyle.Minute.PriceColor = "#ffffff";
    blackStyle.UpBarColor = "#ff3c39";
    blackStyle.DownBarColor = "#00ffff";
    Chart.JSChart.SetStyle(blackStyle);
    let resource = Chart.JSChart.GetResource();
    resource.FrameSplitPen = "rgba(220,20,60,0.3)";
    resource.FrameBorderPen = "rgba(220,20,60,0.3)";
    resource.FrameLogo.Text = null;
    resource.Frame.YTextPadding = [8, 8];
    resource.Frame.XBottomOffset = 2;
    resource.FrameSplitTextColor = "#ff3c39";
    resource.CorssCursorBGColor = "#000";
    option.NetworkFilter = NetworkFilter;
    let chart = Chart.JSChart.Init(hqchart.value);
    chart.SetOption(option);
    chart.AddEventCallback({
        event: Chart.JSCHART_EVENT_ID.ON_FORMAT_CORSSCURSOR_Y_TEXT,
        callback: (event, data, obj) => { OnFormatCorssCursorYText(event, data, obj); }
    });
    chart.AddEventCallback({
        event: Chart.JSCHART_EVENT_ID.ON_FORMAT_CORSSCURSOR_X_TEXT,
        callback: (event, data, obj) => { OnFormatCorssCursorXText(event, data, obj); }
    });
    chart.AddEventCallback({
        event: Chart.JSCHART_EVENT_ID.ON_FINISH_MOVE_DRAWPICTURE,
        callback: (event, data, obj) => { getYvalue(event, data, obj); }
    });
    chart.AddEventCallback({
        event: Chart.JSCHART_EVENT_ID.ON_CLICK_DRAWPICTURE,
        callback: (event, data) => { xuanZhongXian(event, data) }
    });
    chart.AddEventCallback({
        event: Chart.JSCHART_EVENT_ID.ON_FINISH_DRAWPICTURE,
        callback: (event, data, obj) => { OnFinishDrawPicture(event, data, obj); }
    });
    KlineOptionInfo.value = option
    ChartObj.Kline = chart;
    ChartObj.Kline.JSChartContainer.UpdateWindowIndex_backup = ChartObj.Kline.JSChartContainer.UpdateWindowIndex;
    ChartObj.Kline.JSChartContainer.UpdateWindowIndex = (index) => { UpdateWindowIndex(index); }
    ChartObj.Kline.JSChartContainer.ChangeIndex_backup = ChartObj.Kline.JSChartContainer.ChangeIndex;
    ChartObj.Kline.JSChartContainer.ChangeIndex = (index, indexName, option) => { ChangeIndexByLocalCache(index, indexName, option, 'kline'); }
}

function UpdateWindowIndex(index) {
    saveWindowIndex('Update')
    ChartObj.Kline.JSChartContainer.UpdateWindowIndex_backup(index)
}

function saveWindowIndex(type) {
    let aryIndex = ChartObj.Kline.GetIndexInfo();    //获取当前所有指标信息
    let newArrIndex = aryIndex.map(item => {
        if (item.WindowIndex == 0) {
            item.Change = true
        }
        item.Close = false
        item.Index = item.Name
        if (targetData[item.Name])
            targetData[item.Name].Args = item.Args
        item = targetData[item.Name] ? { ...item, ...targetData[item.Name] } : item
        return item
    })
    localStorage.setItem('klineWindowIndexIndex', JSON.stringify(newArrIndex))
    if (type == "Update") {
        let targetObjPath = path.resolve(__dirname, '../../../../../../static/target/target.json');
        if (process.env.NODE_ENV == 'production') {
            targetObjPath = path.resolve(__dirname, '../../static/target/target.json');
        }

        const contentToWrite = `${JSON.stringify(targetData, null, 2)}`;
        fs.writeFile(targetObjPath, contentToWrite, 'utf8', (err) => {
            if (err) {
                console.error('Error writing file:', err);
                return;
            }
            console.log('File written successfully.');
        });
    }
}
function ChangeIndexByLocalCache(index, indexName, option, type) {
    let targetOption = targetData[indexName]
    let canvas = type == "minute" ? ChartObj.zoushi : ChartObj.Kline
    if (targetOption) {
        canvas.ChangeScriptIndex(index, targetOption)
    } else {
        targetOption = {
            "Name": indexName,
            "WindowIndex": index,
            "IsOverlay": false,
            "Close": false,
            "Index": indexName
        }
        canvas.JSChartContainer.ChangeIndex_backup(index, indexName, targetOption)
    }
    if (type == "minute") {
        localStorage.setItem('MinuWindowIndexIndex', JSON.stringify(targetOption))
    } else {
        saveByLocalCache(index, targetOption)
    }
}

function saveByLocalCache(index, option) {
    console.log('option', option);

    let list = localStorage.getItem('klineWindowIndexIndex') ? JSON.parse(localStorage.getItem('klineWindowIndexIndex')) : DefaultTarget
    list[index] = option
    localStorage.setItem('klineWindowIndexIndex', JSON.stringify(list))

}
function UpdateMinuWindowIndex(index) {
    // saveMinuWindowIndex()
    ChartObj.zoushi.JSChartContainer.UpdateWindowIndex_backup(index)
}
// function saveMinuWindowIndex() {
//     let aryIndex = ChartObj.zoushi.GetIndexInfo();    //获取当前所有指标信息
//     console.log('aryIndex', aryIndex);

//     let newArrIndex = aryIndex.map(item => {
//         if (item.WindowIndex == 0) {
//             item.Change = false
//         }
//         item.Close = false
//         item.Index = item.Name
//         return item
//     })
//     localStorage.setItem('MinuWindowIndexIndex', JSON.stringify(newArrIndex))
// }

const CreateMinuteChart = () => {
    ClearChart()
    Chart.MARKET_SUFFIX_NAME.GetETDecimal = () => {
        if (KlineArr.value.length > 0) {
            let open = storeChart.selecteHangeQingData.closedYes || 0
            let num = open && String(open).indexOf('.') != -1 ? String(open).split('.')[1].length : 0
            return Number(num);
        }
        return 0;
    }

    let MinuOptionWindows = JSON.parse(localStorage.getItem('MinuWindowIndexIndex'))
    if (JSON.stringify(MinuOptionWindows) == '{}') {
        MinuteOption.Windows = []
    } else if (MinuOptionWindows == null) {
        MinuteOption.Windows = [{
            "Name": "RSI",
            "Close": false,
            "Description": "相对强弱指标",
            "IsMainIndex": false,
            "Args": [
                {
                    "Name": "N1",
                    "Value": 7
                },
                {
                    "Name": "N2",
                    "Value": 14
                }
            ],
            "Script": "LC:=REF(CLOSE,1);\nRSI1:SMA(MAX(CLOSE-LC,0),N1,1)/SMA(ABS(CLOSE-LC),N1,1)*100;\nRSI2:SMA(MAX(CLOSE-LC,0),N2,1)/SMA(ABS(CLOSE-LC),N2,1)*100;"
        }]
    } else {
        MinuteOption.Windows = [MinuOptionWindows]
    }

    let option = MinuteOption;
    option.ExtendChart = [
        {
            Name: "MinuteTooltip",
            Create: () => {
                return new CustomTooltipMinu();
            }
        }
    ]
    option.Symbol = storeChart.klineCycle + '.sz';
    let blackStyle = Chart.HQChartStyle.GetStyleConfig(
        Chart.STYLE_TYPE_ID.BLACK_ID
    );
    blackStyle.CorssCursorVPenColor = "rgba(255,255,255,0.9)";
    blackStyle.CorssCursorHPenColor = "rgba(255,255,255,0.9)";
    blackStyle.CorssCursorBGColor = "rgba(0,0,0,1)";
    blackStyle.Minute.PriceColor = "#ffffff";
    blackStyle.UpBarColor = "#ff3c39";
    blackStyle.DownBarColor = "#00ffff";
    Chart.JSChart.SetStyle(blackStyle);
    let resource = Chart.JSChart.GetResource();
    resource.Minute.VolBarColor = "#ffff00";
    resource.FrameSplitPen = "rgba(220,20,60,0.3)";
    resource.FrameBorderPen = "rgba(220,20,60,0.3)";
    resource.FrameSplitTextColor = "#ff3c39";
    resource.CorssCursorBGColor = "#000";
    resource.FrameLogo.Text = null;
    let minuteCoordinateData =
        Chart.JSChart.GetMinuteCoordinateData();
    let minuteStringData = Chart.JSChart.GetMinuteTimeStringData();
    minuteStringData.GetET = () => {
        return CreateSHSZData();
    }; //替换交易时间段
    minuteCoordinateData.GetETData = (upperSymbol, width) => {
        return GetSHSZData(upperSymbol, width);
    }; //替换X轴刻度信息
    option.NetworkFilter = NetworkFilter;
    let chart = Chart.JSChart.Init(hqchart.value);
    chart.SetOption(option);
    chart.AddEventCallback({
        event: Chart.JSCHART_EVENT_ID.ON_FORMAT_CORSSCURSOR_Y_TEXT,
        callback: (event, data, obj) => { OnFormatCorssCursorYTextMinuteChart(event, data, obj); }
    });
    chart.AddEventCallback({
        event: Chart.JSCHART_EVENT_ID.ON_FORMAT_CORSSCURSOR_X_TEXT,
        callback: (event, data, obj) => { OnFormatCorssCursorXText(event, data, obj); }
    });
    chart.AddEventCallback({
        event: Chart.JSCHART_EVENT_ID.ON_FINISH_MOVE_DRAWPICTURE,
        callback: (event, data, obj) => { getYvalue(event, data, obj); }
    });
    chart.AddEventCallback({
        event: Chart.JSCHART_EVENT_ID.ON_CLICK_DRAWPICTURE,
        callback: (event, data) => { xuanZhongXian(event, data) }
    });
    chart.AddEventCallback({
        event: Chart.JSCHART_EVENT_ID.CLOSE_INDEX_WINDOW,
        callback: (event, data, obj) => { console.log(`output->关闭指标`, data, obj) }
    });
    MinuOptionInfo.value = option
    ChartObj.zoushi = chart;
    ChartObj.zoushi.JSChartContainer.ChangeIndex_backup = ChartObj.zoushi.JSChartContainer.ChangeIndex;
    ChartObj.zoushi.JSChartContainer.ChangeIndex = (index, indexName, option) => { ChangeIndexByLocalCache(index, indexName, option, 'minute'); }
    ChartObj.zoushi.JSChartContainer.UpdateWindowIndex_backup = ChartObj.zoushi.JSChartContainer.UpdateWindowIndex;
    ChartObj.zoushi.JSChartContainer.UpdateWindowIndex = (index) => { UpdateMinuWindowIndex(index); }
}
const NetworkFilter = (data, callback) => {
    data.PreventDefault = true;
    NetworkFilterCallback.value = callback
    switch (data.Name) {
        case "KLineChartContainer::ReqeustHistoryMinuteData": //分钟全量数据下载
            callback(setKlineHqchart(storeChart.KlineData));
            break;
        case "KLineChartContainer::RequestDragMinuteData": //拖拽分钟更新
            if (KlineArr.value.length > 0) storeChart.hangqingMqtt.publish(`40;${storeMain.selectHeyue.heyue_bh};${props.minLineVal};${storeChart.hangqingMqtt.clientId};${KlineArr.value[0].time};`)
            break;
        case "KLineChartContainer::RequestHistoryData": //日线全量数据下载
            callback(setKlineHqchart(storeChart.KlineData));
            break;
        case "MinuteChartContainer::RequestMinuteData": //分时图
            callback(setMinuteHqchart(KlineArr.value))
            break;
        case "MinuteChartContainer::RequestHistoryMinuteData": //多日分时数据
            callback(setHistoryMinuteHqchart(KlineArr.value))
            break;
    }
}
const setKlineHqchart = (event) => {
    let objData = event.map(item => {
        if (klineDtartDate.value) {
            const date = new Date(`${klineDtartDate.value}T00:00:00`);
            let timestamp = date.getTime();
            if (timestamp > item.time * 1000) {
                return ''
            }
        } else {
            if (istodayDataKline.value && storeChart.klineCycle != 0) {
                const currentDate = new Date();
                currentDate.setHours(0, 0, 0, 0);
                const timestamp = currentDate.getTime();
                if (timestamp > item.time * 1000) {
                    return ''
                }
            }
        }
        return [Number(moment(item.time * 1000).format("YYYYMMDD")), null, item.open * 1, item.high * 1, item.low * 1, item.close * 1, item.volume * 1, null, Number(moment(item.time * 1000).format("HHmm"))]
    })
    objData = objData.filter(item => item)
    let obj = {
        code: 0,
        "symbol": `${storeChart.klineCycle}.ET`,
        "name": `${storeChart.klineCycle}.ET`,
        ver: 2,
        data: objData
    }
    return obj
}
const setMinuteHqchart = (event) => {
    let totalAmount = 0;
    let totalVal = 0;
    let minute = event.map(item => {
        if (item.time < storeChart.TradetimeList[0].start_time) return ''
        totalVal += item.volume * 1;
        totalAmount += item.close * item.volume;
        let avprice = totalAmount / totalVal;
        if (totalAmount == 0) {
            avprice = (item.close * 1).toFixed(2) * 1;
        }
        return {
            "date": moment(item.time * 1000).format("YYYYMMDD"),
            "time": moment(item.time * 1000).format("HHmmss"),
            "open": item.open * 1,
            "high": item.high * 1,
            "low": item.low * 1,
            "price": item.close * 1,
            "vol": item.volume * 1,
            "amount": item.close * item.volume,
            "avprice": avprice
        }

    })
    minute = minute.filter(item => (item))
    let obj = {
        code: 0,
        stock: [
            {
                "symbol": `${storeChart.klineCycle}.ET`,
                "name": `${storeChart.klineCycle}.ET`,
                "yclose": storeChart.selecteHangeQingData.closedYes,
                "date": moment(storeChart.selecteHangeQingData.timestamp * 1000).format("YYYYMMDD"),
                minute
            }
        ]
    }
    console.log(`output->obj`, obj)
    return obj
}

function getDUoRiMinuList(dateTime, val, start_time, end_time) {
    let obj = {
        close: 0,
        yclose: 0,
        date: Number(dateTime),
        minute: []
    }
    let totalAmount = 0;
    let totalVal = 0;
    obj.minute = val.map(item => {
        if (item.time >= start_time && item.time <= end_time) {
            totalAmount = item.close * item.volume
            totalVal = item.volume
            obj.close = item.close
            return [Number(moment(item.time * 1000).format("HHmm")), item.open, item.close, item.high, item.low, item.volume, null, Number((totalAmount / totalVal).toFixed(2)), Number(moment(item.time * 1000).format("YYYYMMDD")), null]
        }
        return false
    })
    obj.minute = obj.minute.filter(item => item)
    return obj
}
const setHistoryMinuteHqchart = (val) => {
    let data = []
    let start_time = storeChart.TradetimeList[0].start_time
    let end_time = storeChart.TradetimeList[storeChart.TradetimeList.length - 1].end_time
    for (let i = 0; i < minuDay.value + 1; i++) {
        if (i == 0) {
            data[i] = getDUoRiMinuList(moment().format('YYYYMMDD'), val, start_time, end_time)
        } else {
            start_time = moment.unix(start_time).subtract(i, 'days').unix();
            end_time = moment.unix(end_time).subtract(i, 'days').unix();
            data[i] = getDUoRiMinuList(moment().subtract(i, 'days').format('YYYYMMDD'), val, start_time, end_time)
        }
    }
    data.forEach((item, index) => {
        if (data[index + 1] && data[index + 1].minute.length >= 1) {
            let minute = data[index + 1].minute
            item.yclose = minute[minute.length - 1][1]
        }
    })
    data.pop()
    let obj = {
        code: 0,
        symbol: storeChart.klineCycle + '.sz',
        name: storeChart.klineCycle,
        updatetime: { date: Number(moment(val[val.length - 1].time * 1000).format("YYYYMMDD")), time: Number(moment(val[val.length - 1].time * 1000).format("hhmmss")) },
        data,
        version: "2.0",
        ticket: 31
    }
    return obj
}

const onDrawXian = (v) => {
    var drawOption =
    {
        LineColor: '#4169E1',    //线段颜色
        LineWidth: 2,            //线段宽度
        PointColor: 'rgb(255,130,71)'    //点颜色
    };
    let name = v
    if (v == '符号') {
        name = 'icon-arrow_up'
    }
    if (v == '竖线') {
        name = '垂直线'
    }
    if (v == '指引线') {
        name = '箭头'
    }
    if (v == '通道线') {
        name = '平行线'
    }
    if (v == '折线') {
        name = 'M头W底'
    }
    if (v == '箱体') {
        name = '箱型线'
    }
    if (v == '三弦线') {
        name = '头肩型'
    }
    if (v == '圆弧') {
        name = '圆弧线'
    }
    if (v == '甘氏线') {
        name = 'FibSpeedResistanceFan'
    }
    if (v == '对称角度线') {
        name = '对称角度'
    }
    if (v == '线性回归带') {
        name = '线形回归带'
    }
    if (v == '回归通道') {
        name = '延长线形回归带'
    }
    if (v == '黄金率') {
        name = '黄金分割'
    }
    if (v == '量度目标') {
        name = 'AB波浪尺'
    }
    if (v == '周期线') {
        name = '斐波那契周期线'
    }
    if (v == '斐波那契时间序列') {
        name = '斐波那契周期线'
    }
    if (v == '斐波那契时间扩展') {
        name = '斐波那契周期线'
    }
    ChartObj.Kline.CreateChartDrawPicture(name, drawOption);
}

const OnSize = () => {
    if (chartKlineDoc.value) {
        const resizeObserver = new ResizeObserver(entries => {
            for (let entry of entries) {
                if (hqchart.value) {
                    const { width, height } = entry.contentRect;
                    hqchart.value.style.width = width + "px";
                    hqchart.value.style.height = height + "px";
                    if (ChartObj.zoushi) ChartObj.zoushi.OnSize();
                    if (ChartObj.Kline) ChartObj.Kline.OnSize();
                }
            }
        });
        resizeObserver.observe(chartKlineDoc.value);
    }
}
const ClearChart = () => {
    if (ChartObj.zoushi) {
        ChartObj.zoushi.ChartDestory();
    }
    if (ChartObj.Kline) {
        ChartObj.Kline.ChartDestory();
    }
    if (hqchart.value) {
        while (hqchart.value.hasChildNodes()) {
            hqchart.value.removeChild(hqchart.value.lastChild);
        }
    }
    ChartObj.zoushi = null;
    ChartObj.Kline = null;
}
const handleRightClick = () => {
    if (ChartObj.Kline) ipcRenderer.send('open-right-click', 'rightClickKline')
    if (ChartObj.zoushi) ipcRenderer.send('open-right-click', 'rightClickMinu')
}

const dblclickChart = () => {
    showToolTip = !showToolTip
    if (ChartObj.zoushi) ChartObj.zoushi.JSChartContainer.EnableShowCorssCursorLine(showToolTip)
    if (ChartObj.Kline) { ChartObj.Kline.JSChartContainer.EnableShowCorssCursorLine(showToolTip) }
}


const OnFormatCorssCursorYTextMinuteChart = (event, data, obj) => {
    if (!showToolTip) obj.PercentageText = '', obj.Text = '';
}

const OnFormatCorssCursorYText = (event, data, obj) => {
    obj.RText = '';
}

const OnFormatCorssCursorXText = (event, data, obj) => {
    if (!showToolTip) obj.Text = '';
}

const CreateSHSZData = () => {
    let TIME_SPLIT = [];
    TIME_SPLIT = storeChart.TradetimeList.map(item => {
        return {
            Start: parseInt(moment(item.start_time * 1000).format("HHmm")),
            End: parseInt(moment(item.end_time * 1000).format("HHmm")),
        }
    })
    var minuteStringData = Chart.JSChart.GetMinuteTimeStringData();
    return minuteStringData.CreateTimeData(TIME_SPLIT);
}
const GetSHSZData = () => {
    let timeCount = 1;
    let Full = [];
    for (let i = 0; i < storeChart.TradetimeList.length; i++) {
        let time = {
            Start:
                new Date(
                    moment().format("YYYY-MM-DD") +
                    ` ${moment(storeChart.TradetimeList[i].start_time * 1000).format(
                        "HH:mm:ss"
                    )}`
                ).getTime() /
                1000 /
                60,
            End:
                new Date(
                    moment().format("YYYY-MM-DD") +
                    ` ${moment(storeChart.TradetimeList[i].end_time * 1000).format(
                        "HH:mm:ss"
                    )}`
                ).getTime() /
                1000 /
                60,
        };

        let onceTimeCount = time.End - time.Start;
        let spliceCount = 60;
        for (let j = 0; j < onceTimeCount; j++) {
            if (j % spliceCount == 0) {
                if (
                    i > 0 &&
                    j == 0 &&
                    storeChart.TradetimeList[i].start_time !=
                    storeChart.TradetimeList[i - 1].end_time
                ) {
                    timeCount += 1;
                }
                Full.push([
                    timeCount + j,
                    0,
                    "rgb(200,200,200)",
                    moment(time.Start * 1000 * 60 + j * 60 * 1000).format("HH:mm"),
                ]);
            }
        }
        timeCount += time.End - time.Start;
    }
    Full.push([
        timeCount,
        0,
        "RGB(200,200,200)",
        moment(
            storeChart.TradetimeList[storeChart.TradetimeList.length - 1].end_time *
            1000
        ).format("HH:mm"),
    ]);

    const SHZE_MINUTE_X_COORDINATE = {
        //完整模式
        Full: Full,
        Count: timeCount, //!! 一共的分钟数据个数，不要填错了
        MiddleCount: parseInt(timeCount / 2), // Count/2 就可以。
        GetData: function () {
            return Full
        },
    };
    return SHZE_MINUTE_X_COORDINATE;
}


var showToolTip = false;
function CustomTooltip() {
    let updateFn = { minute: false }
    this.newMethod = Chart.KLineTooltipPaint; //派生
    this.newMethod();
    delete this.newMethod;

    this.Draw = function () {
        // 判断当前是否显示tooltip
        if (!showToolTip) return;
        this.KLineTitlePaint = this.HQChart.TitlePaint[0];
        var klineData = this.KLineTitlePaint.GetCurrentKLineData();
        if (!klineData) return;
        this.Font = [12 * Chart.GetDevicePixelRatio() + "px 微软雅黑"];
        //设置tooltip高度, 宽度
        this.Canvas.font = this.Font[0];
        var maxText = "99999.99"; //最长的输出
        this.Width = this.Canvas.measureText(maxText).width;
        this.Height = (this.LineHeight + 4) * 16;
        this.Top = 0;
        this.Left = 0;
        this.CalculateShowPosition();
        this.DrawBG();
        this.DrawItem(klineData);
        this.DrawBorder();
    };

    //显示当前数据
    this.DrawItem = function (item) {
        var defaultfloatPrecision = 2; //价格小数位数
        var left = this.GetLeft() + 2;
        var top = this.GetTop() + 3;
        var color1 = "#ff3c39";
        var color2 = "#04fc05";
        var color3 = "#ffff00";
        var upNum = (item.Close - item.Open).toFixed(defaultfloatPrecision);
        var upNumChg =
            (((item.Close - item.Open) / item.Open) * 100).toFixed(
                defaultfloatPrecision
            ) + "%";
        this.Canvas.textBaseline = "top";
        this.Canvas.textAlign = "left";
        this.Canvas.font = this.Font[0];
        //日期
        var text = item.Date.toString();
        let date = text.substr(4, item.Date.length);
        if (item.Time || item.Position) {
            let time = (item.Time || item.Position).toString();
            top += 4;
            this.Canvas.fillStyle = color3;
            let DateText =
                item.Date != "Invalid date"
                    ? `${date[0]}${date[1]} / ${date[2]}${date[3]}`
                    : "--";
            this.Canvas.fillText(DateText, left, top);
            top += this.LineHeight + 4;
            time = time.length == 4 ? time : '0' + time
            let TimeText =
                item.Time != "Invalid date"
                    ? `${time[0]}${time[1]}: ${time[2]}${time[3]}`
                    : "--";
            this.Canvas.fillText(TimeText, left, top);
        } else {
            top += 4;
            this.Canvas.fillStyle = color3;
            let date = `${item.Date}`;
            this.Canvas.fillText(
                date.slice(4, 6) + "/" + date.slice(6, 8),
                left,
                top
            );
            top += this.LineHeight + 4;
            this.Canvas.fillText("00:00", left, top);
        }

        //开盘价
        if (!updateFn.minute) {
            this.Canvas.fillStyle = this.TitleColor;
            top += this.LineHeight + 4;
            this.Canvas.fillText("开盘", left, top);
            top += this.LineHeight + 4;
            text = item.Open.toFixed(defaultfloatPrecision);
            let OpenText = isNaN(item.Open) ? "--" : text;
            this.Canvas.fillText(OpenText, left, top);
        }

        //最高价

        if (!updateFn.minute) {
            this.Canvas.fillStyle = this.TitleColor;
            top += this.LineHeight + 4;
            this.Canvas.fillText("最高", left, top);
            top += this.LineHeight + 4;
            this.Canvas.fillStyle = color1;
            text = item.High.toFixed(defaultfloatPrecision);
            let HighText = isNaN(item.High) ? "--" : text;
            this.Canvas.fillText(HighText, left, top);
        }

        //最低价
        if (!updateFn.minute) {
            this.Canvas.fillStyle = this.TitleColor;
            top += this.LineHeight + 4;
            this.Canvas.fillText("最低", left, top);
            top += this.LineHeight + 4;
            this.Canvas.fillStyle = color2;
            text = item.Low.toFixed(defaultfloatPrecision);
            let LowText = isNaN(item.High) ? "--" : text;
            this.Canvas.fillText(LowText, left, top);
        }

        //收盘价
        if (!updateFn.minute) {
            this.Canvas.fillStyle = this.TitleColor;
            top += this.LineHeight + 4;
            this.Canvas.fillText("收盘", left, top);
            top += this.LineHeight + 4;
            if (upNum <= 0) {
                this.Canvas.fillStyle = color2;
            } else {
                this.Canvas.fillStyle = color1;
            }
            text = item.Close.toFixed(defaultfloatPrecision);
            let CloseText = isNaN(item.Close) ? "--" : text;
            this.Canvas.fillText(CloseText, left, top);
        }

        // 涨跌
        top += this.LineHeight + 4;
        this.Canvas.fillStyle = this.TitleColor;
        this.Canvas.fillText("涨跌", left, top);
        top += this.LineHeight + 4;
        upNum = isNaN(item.Open) ? "--" : upNum;
        this.Canvas.fillText(upNum, left, top);

        // 涨跌幅
        if (!updateFn.minute) {
            top += this.LineHeight + 4;
            this.Canvas.fillStyle = this.TitleColor;
            this.Canvas.fillText("涨跌幅", left, top);
            top += this.LineHeight + 4;
            upNumChg = isNaN(item.Open) ? "--" : upNumChg;
            this.Canvas.fillText(upNumChg, left, top);
        }

        // 成交量
        top += this.LineHeight + 4;
        this.Canvas.fillStyle = this.TitleColor;
        this.Canvas.fillText("成交量", left, top);
        top += this.LineHeight + 4;
        let VolText = isNaN(item.Vol) ? "--" : item.Vol;
        this.Canvas.fillText(VolText, left, top);
    };
    this.CalculateShowPosition = function () {
        this.ShowPosition = 0; // 显示位置 0 左 1右边
    };
}
function CustomTooltipMinu() {
    let updateFn = { minute: false }
    this.newMethod = Chart.KLineTooltipPaint; //派生
    this.newMethod();
    delete this.newMethod;

    this.Draw = function () {
        // 判断当前是否显示tooltip
        if (!showToolTip) return;
        this.KLineTitlePaint = this.HQChart.TitlePaint[0];
        var klineData = this.KLineTitlePaint.GetCurrentKLineData();
        if (!klineData) return;
        this.Font = [12 * Chart.GetDevicePixelRatio() + "px 微软雅黑"];
        //设置tooltip高度, 宽度
        this.Canvas.font = this.Font[0];
        var maxText = "99999.99"; //最长的输出
        this.Width = this.Canvas.measureText(maxText).width;
        this.Height = (this.LineHeight + 4) * 16;
        this.Top = 0;
        this.Left = 0;
        this.CalculateShowPosition();
        this.DrawBG();
        this.DrawItem(klineData);
        this.DrawBorder();
    };

    //显示当前数据
    this.DrawItem = function (item) {
        var defaultfloatPrecision = 2; //价格小数位数
        var left = this.GetLeft() + 2;
        var top = this.GetTop() + 3;
        var color1 = "#ff3c39";
        var color2 = "#04fc05";
        var color3 = "#ffff00";
        var upNum = (item.Close - item.Open).toFixed(defaultfloatPrecision);
        var upNumChg =
            (((item.Close - item.Open) / item.Open) * 100).toFixed(
                defaultfloatPrecision
            ) + "%";
        this.Canvas.textBaseline = "top";
        this.Canvas.textAlign = "left";
        this.Canvas.font = this.Font[0];
        //日期
        var text = item.Date.toString();
        let date = text.substr(4, item.Date.length);
        if (item.Time || item.Position) {
            top += 4;
            this.Canvas.fillStyle = color3;
            let DateText =
                item.Date != "Invalid date"
                    ? `${date[0]}${date[1]} / ${date[2]}${date[3]}`
                    : "--";
            this.Canvas.fillText(DateText, left, top);
            top += this.LineHeight + 4;
            let Time = ''
            if (String(item.Time).length >= 4) {
                Time = String(item.Time)
            }
            if (String(item.Time).length == 3) {
                Time = '0' + String(item.Time)
            }
            if (String(item.Time).length == 2) {
                Time = '00' + String(item.Time)
            }
            if (String(item.Time).length == 1) {
                Time = '000' + String(item.Time)
            }
            let TimeText =
                item.Time != "Invalid date"
                    ? `${Time[0]}${Time[1]}: ${Time[2]}${Time[3]}`
                    : "--";
            this.Canvas.fillText(TimeText, left, top);
        } else {
            top += 4;
            this.Canvas.fillStyle = color3;
            let date = `${item.Date}`;
            this.Canvas.fillText(
                date.slice(4, 6) + "/" + date.slice(6, 8),
                left,
                top
            );
            top += this.LineHeight + 4;
            this.Canvas.fillText("00:00", left, top);
        }

        //开盘价
        if (!updateFn.minute) {
            this.Canvas.fillStyle = this.TitleColor;
            top += this.LineHeight + 4;
            this.Canvas.fillText("开盘", left, top);
            top += this.LineHeight + 4;
            text = item.Open.toFixed(defaultfloatPrecision);
            let OpenText = isNaN(item.Open) ? "--" : text;
            this.Canvas.fillText(OpenText, left, top);
        }

        //最高价

        if (!updateFn.minute) {
            this.Canvas.fillStyle = this.TitleColor;
            top += this.LineHeight + 4;
            this.Canvas.fillText("最高", left, top);
            top += this.LineHeight + 4;
            this.Canvas.fillStyle = color1;
            text = item.High.toFixed(defaultfloatPrecision);
            let HighText = isNaN(item.High) ? "--" : text;
            this.Canvas.fillText(HighText, left, top);
        }

        //最低价
        if (!updateFn.minute) {
            this.Canvas.fillStyle = this.TitleColor;
            top += this.LineHeight + 4;
            this.Canvas.fillText("最低", left, top);
            top += this.LineHeight + 4;
            this.Canvas.fillStyle = color2;
            text = item.Low.toFixed(defaultfloatPrecision);
            let LowText = isNaN(item.High) ? "--" : text;
            this.Canvas.fillText(LowText, left, top);
        }

        //收盘价
        if (!updateFn.minute) {
            this.Canvas.fillStyle = this.TitleColor;
            top += this.LineHeight + 4;
            this.Canvas.fillText("收盘", left, top);
            top += this.LineHeight + 4;
            if (upNum <= 0) {
                this.Canvas.fillStyle = color2;
            } else {
                this.Canvas.fillStyle = color1;
            }
            text = item.Close.toFixed(defaultfloatPrecision);
            let CloseText = isNaN(item.Close) ? "--" : text;
            this.Canvas.fillText(CloseText, left, top);
        }

        // 涨跌
        top += this.LineHeight + 4;
        this.Canvas.fillStyle = this.TitleColor;
        this.Canvas.fillText("涨跌", left, top);
        top += this.LineHeight + 4;
        upNum = isNaN(item.Open) ? "--" : upNum;
        this.Canvas.fillText(upNum, left, top);

        // 涨跌幅
        if (!updateFn.minute) {
            top += this.LineHeight + 4;
            this.Canvas.fillStyle = this.TitleColor;
            this.Canvas.fillText("涨跌幅", left, top);
            top += this.LineHeight + 4;
            upNumChg = isNaN(item.Open) ? "--" : upNumChg;
            this.Canvas.fillText(upNumChg, left, top);
        }

        // 成交量
        top += this.LineHeight + 4;
        this.Canvas.fillStyle = this.TitleColor;
        this.Canvas.fillText("成交量", left, top);
        top += this.LineHeight + 4;
        let VolText = isNaN(item.Vol) ? "--" : item.Vol;
        this.Canvas.fillText(VolText, left, top);
    };
    this.CalculateShowPosition = function () {
        this.ShowPosition = 0; // 显示位置 0 左 1右边
    };
}
</script>

<style scoped lang="less">
.chart_Kline {
    width: 100%;
    height: 100%;

    .hqchart {
        background-color: black;
        position: relative;
        height: 100%;
    }
}

:deep(.jchart-select-section),
:deep(.target-panel),
:deep(.parameter) {
    color: #303133;
}

:deep(.row-line::-webkit-inner-spin-button,
    .row-line::-webkit-outer-spin-button) {
    -webkit-appearance: none;
    margin: 0;
}
</style>
